package shoppingmall.common.captchaCode;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;
import shoppingmall.common.dto.Result;
import shoppingmall.common.utils.PictureCaptchaGenerator;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

@SuppressWarnings({"all"})
@Slf4j
@RestController
public class PictureCaptchaController {

    /**
     * 图片验证码生成接口1:直接返回图片，以IO流的形式
     * @param response
     * @throws IOException
     */
    @GetMapping("/captcha/picture")
    public void generateCaptcha(HttpServletResponse response) throws IOException {
        log.info("获取图片验证码-->直接输出图片IO流");
        String captchaCode = generateRandomCode();  //随机四位数验证码
        BufferedImage image = PictureCaptchaGenerator.generateCaptchaImage(captchaCode);  //生成BufferedImage对象
        response.setContentType("image/png");  //设置响应头
        ImageIO.write(image, "png", response.getOutputStream());  //IO流写入通道
    }


    /**
     * 图片验证码生成接口2: 返回base64编码的图片
     */
    @GetMapping("/captcha/picture/base64")
    public Result generateCaptchaByBase64 (HttpServletResponse response, HttpServletRequest request) {
        log.info("获取图片验证码-->图片转为base64方式");
        String captchaCode = generateRandomCode();  //随机四位数验证码
        BufferedImage image = PictureCaptchaGenerator.generateCaptchaImage(captchaCode);  //生成BufferedImage对象
        String imageBase64Prefix = "data:image/png;base64,";
        String imageBase64 = imageBase64Prefix + encodeImageToBase64(image);  //获取base64编码的图片
        //在session中存储图片验证码
        request.getSession().setAttribute("captchaCode",captchaCode.toLowerCase());
        return Result.success(imageBase64);
    }

    /**
     * 随机生成四位数验证码
     * @return
     */
    private String generateRandomCode() {
        String codeStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            code.append(codeStr.charAt(random.nextInt(codeStr.length())));
        }
        return code.toString();
    }

    /**
     * 将BufferedImage转为base64
     */
    public String encodeImageToBase64(BufferedImage image) {
        byte[] imageBytes = null;
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            imageBytes = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(imageBytes);
    }

}
